from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

import false_email
from config import SERVICE_ARGS


class GetPages(object):
    send_mail = false_email.FalseEmail()

    def get_pages(self, num_retries=2):
        driver = webdriver.PhantomJS(service_args=SERVICE_ARGS)

        driver.get('https://www.douyu.com/directory/all')

        wait = WebDriverWait(driver, 10)
        try:
            submit = wait.until(
                EC.element_to_be_clickable(
                    (By.CSS_SELECTOR, "#container > div.normallevel-lead > div.normallevel-box > a"))
            )
            submit.click()
        except:
            print('no click')
        try:
            pages = wait.until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "#J-pager > a:nth-child(11)"))
            )
            return int(pages.text)
        except:
            self.send_mail.send_email(content="error pages", name=int(num_retries))
            if num_retries > 0:
                return self.get_pages(num_retries - 1)
        finally:
            driver.quit()


if __name__ == '__main__':
    GetPages().get_pages()
